{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "9dfe6f8b-308c-4bd8-891e-51f7f1db5982",
   "metadata": {},
   "outputs": [],
   "source": [
    "import cv2\n",
    "import numpy as np"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "633f6ae7-b824-4306-bd93-b07c0baf0856",
   "metadata": {},
   "outputs": [],
   "source": [
    "\"\"\"\n",
    "图像灰色处理\n",
    "frame: 图像帧（ndarray）\n",
    "return: 处理过后的帧（ndarray）\n",
    "\"\"\"\n",
    "def image_sepia(frame):\n",
    "    sep_image = np.zeros(frame.shape)\n",
    "    r = frame[:,:,0]\n",
    "    g = frame[:,:,1]\n",
    "    b = frame[:,:,2]\n",
    "    sep_image[:,:,0] = r * 0.393 + g * 0.769 + b * 0.189#r通道计算\n",
    "    sep_image[:,:,1] = r * 0.349 + g * 0.686 + b * 0.168#b通道计算\n",
    "    sep_image[:,:,2] = r * 0.272 + g * 0.534 + b * 0.131#g通道计算\n",
    "    sep_image = np.clip(sep_image, 0, 255).astype(np.uint8)\n",
    "    return sep_image"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "15bb163d-dcdf-484c-9c42-d56209473157",
   "metadata": {},
   "outputs": [],
   "source": [
    "def image_binary(frame):\n",
    "    r_frame = np.where(frame[:,:,0] > 127, 255, 0) #图像二值化\n",
    "    r_frame = r_frame.astype(np.uint8)\n",
    "    return r_frame"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "3d362874-f81c-4a5e-a3b6-243bb737cbfe",
   "metadata": {},
   "outputs": [],
   "source": [
    "def r2b(frame):\n",
    "    pass"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "a1c93ee5-ca72-4526-ae21-5166845d0d56",
   "metadata": {},
   "outputs": [],
   "source": [
    "cap = cv2.VideoCapture(0)#获取摄像头\n",
    "while cap.isOpened():\n",
    "    ret, frame = cap.read()#通过摄像头读取每一帧\n",
    "    frame = cv2.flip(frame, 180)#水平翻转\n",
    "    # frame = image_sepia(frame)\n",
    "    frame = image_binary(frame)\n",
    "    cv2.namedWindow(\"Hello Opencv\")#对窗口命名\n",
    "    cv2.imshow(\"Hello Opencv\", frame)\n",
    "    key = cv2.waitKey(1)\n",
    "    if key == 27:#ascii码，esc\n",
    "        break\n",
    "cap.release()#释放摄像头\n",
    "cv2.destroyAllWindows()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "dc40c78b-ba25-4420-add1-03e55bf190a7",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.10.0"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
